package com.bdqn.ch10.config.shiro;


import com.bdqn.ch10.pojo.SysUser;
import com.bdqn.ch10.service.SysUserService;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private SysUserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用MyShiroRealm.doGetAuthorizationInfo获取权限信息");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo();
        info.addRole(userService.getRole().getRoleName());
        info.addStringPermission("用户列表");
        if ("管理员".equals(userService.getRole().getRoleName())){
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("用户删除");
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShirorRealm.doGetAuthenticationInfo获取身份证信息！");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        SysUser user = userService.getUserByUserName(usrName);
        if (user == null){
            throw new UnknownAccountException();
        }
        if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user , user.getUsrPassword() , getName());
        return info;
    }


}
